package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.ArticleDto;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.ResultSet;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/ydd_article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CateService cateService;

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    /**
     * 分页条件查询
     * @param start_time
     * @param end_time
     * @param title
     * @param cateid
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public ResultData list(Long start_time,Long end_time,String title,Long cateid,Integer page,Integer limit){
        //log.info(start_time.toString());
        //log.info(end_time.toString());
        //构建分页构造器
        Page<Article> pageInfo = new Page<>(page, limit);
        Page<ArticleDto> dtoPage = new Page<>();
        //构建条件构造器
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //查询条件
        queryWrapper.like(title != null,Article::getTitle,title);
        queryWrapper.eq(cateid != null ,Article::getCateid,cateid);
        queryWrapper.between(start_time !=null & end_time != null ,Article::getCreate_date,start_time,end_time);
        queryWrapper.orderByDesc(Article::getCreate_date);
        articleService.page(pageInfo,queryWrapper);

        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Article> articleList = pageInfo.getRecords();
        List<ArticleDto> articleDtoList = articleList.stream().map(item->{
            ArticleDto articleDto = new ArticleDto();
            BeanUtils.copyProperties(item,articleDto);
            Integer itemCateid = Math.toIntExact(item.getCateid());
            Cate cate = cateService.getById(itemCateid);
            articleDto.setCatename(cate.getCateName());
            return articleDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(articleDtoList);
        return ResultData.ok("", PageResult.init(dtoPage.getTotal(), dtoPage.getSize(), dtoPage.getCurrent(), dtoPage.getRecords()));
    }

    /**
     * 添加方法
     * @param article
     * @return
     */
//    @PostMapping("add")
//    public ResultData add(@RequestBody Article article){
//
//        articleService.save(article);
//        return ResultData.ok("添加成功",article);
//    }
    @PostMapping("add")
    public ResultData add(@RequestBody Article article) {
        log.info("新增启动");
        LambdaQueryWrapper<Article> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Article::getTitle,article.getTitle());
        Article article1 = articleService.getOne(lqw);
        if (article1 != null) {
            throw new BusinessException("该文章名已存在，请重新命名");
        }
        //权限管理
        LambdaQueryWrapper<Role> qlw = new LambdaQueryWrapper<>();
        //获取用户登陆的id  转化为string类型  --前端页码传来的值带有【】 ""  所以要去除点
        String userId = UserHolder.getUserId();
        User user1 = userService.getById(userId);
        //分割
        String strip = StringUtils.strip(user1.getRole_id(), "[]");
        String[] split = strip.split(",");
        for (int i = 0; i < split.length; i++) {
            //代替    --去除
            split[i] = StringUtils.replace(split[i], "\"", "");
        }
        qlw.in(Role::getId, split);
        List<Role> list = roleService.list(qlw);
        List<String> collect = list.stream().map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        LambdaQueryWrapper<RoleMenu> qlw2 = new LambdaQueryWrapper<>();
        qlw2.in(RoleMenu::getRoleId, collect);
        List<RoleMenu> list1 = roleMenuService.list(qlw2);
        for (RoleMenu roleMenu : list1) {
            String menuId = roleMenu.getMenuId();
            Menu menu = menuService.getById(menuId);
            //一级权限
            if ("内容管理".equals(menu.getTitle())) {
                LambdaQueryWrapper<Menu> qlw3 = new LambdaQueryWrapper<>();
                qlw3.eq(Menu::getPid, menuId);
                List<Menu> list2 = menuService.list(qlw3);
                //二级缓存
                for (Menu menu1 : list2) {
                    if ("标签管理".equals(menu1.getTitle())) {
                        LambdaQueryWrapper<Menu> qwl4 = new LambdaQueryWrapper<>();
                        qwl4.eq(Menu::getPid, menu1.getId());
                        List<Menu> list3 = menuService.list(qwl4);
                        for (Menu menu2 : list3) {
                            //三级缓存
                            if ("增加".equals(menu2.getTitle())) {

                                articleService.save(article);

                                return ResultData.ok("新增成功", article);
                            }
                        }
                    }
                }
            }
        }

        return ResultData.error("权限不足不能添加");
    }

    /**
     *  删除方法
     * @param id
     * @return
     */
//    @GetMapping("/del")
//    public ResultData del(Long id){
//        articleService.removeById(id);
//        return ResultData.ok("","删除成功");
//    }
    @GetMapping("del")
    public ResultData del(Integer id) {
        log.info("文章删除启动");
        Article article = articleService.getById(id);
        if ("1".equals(article.getDefault_data())) {
            return ResultData.error("默认数据无法删除");
        }
        //权限管理
        LambdaQueryWrapper<Role> qlw = new LambdaQueryWrapper<>();
        //获取用户登陆的id  转化为string类型  --前端页码传来的值带有【】 ""  所以要去除点
        String userId = UserHolder.getUserId();
        User user1 = userService.getById(userId);
        //分割
        String strip = StringUtils.strip(user1.getRole_id(), "[]");
        String[] split = strip.split(",");
        for (int i = 0; i < split.length; i++) {
            //代替    --去除
            split[i] = StringUtils.replace(split[i], "\"", "");
        }
        qlw.in(Role::getId, split);
        List<Role> list = roleService.list(qlw);
        List<String> collect = list.stream().map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        LambdaQueryWrapper<RoleMenu> qlw2 = new LambdaQueryWrapper<>();
        qlw2.in(RoleMenu::getRoleId, collect);
        List<RoleMenu> list1 = roleMenuService.list(qlw2);
        for (RoleMenu roleMenu : list1) {
            String menuId = roleMenu.getMenuId();
            Menu menu = menuService.getById(menuId);
            //一级权限
            if ("内容管理".equals(menu.getTitle())) {
                LambdaQueryWrapper<Menu> qlw3 = new LambdaQueryWrapper<>();
                qlw3.eq(Menu::getPid, menuId);
                List<Menu> list2 = menuService.list(qlw3);
                //二级缓存
                for (Menu menu1 : list2) {
                    if ("文章管理".equals(menu1.getTitle())) {
                        LambdaQueryWrapper<Menu> qwl4 = new LambdaQueryWrapper<>();
                        qwl4.eq(Menu::getPid, menu1.getId());
                        List<Menu> list3 = menuService.list(qwl4);
                        for (Menu menu2 : list3) {
                            //三级缓存
                            if ("删除".equals(menu2.getTitle())) {
                                articleService.removeById(id);
                                return ResultData.ok("删除成功", "");
                            }
                        }
                    }
                }
            }
        }

        return ResultData.error("权限不足无法删除！");
    }


}
